<?php
/**
 * Simplified Test Script for SixShop Maker Bundle
 * Tests the actual working functionality
 */

// Autoload classes
if (file_exists(__DIR__ . '/../vendor/autoload.php')) {
    require __DIR__ . '/../vendor/autoload.php';
} elseif (file_exists(__DIR__ . '/../../../../autoload.php')) {
    require __DIR__ . '/../../../../autoload.php';
} else {
    echo "Error: Composer autoload not found.\n";
    exit(1);
}

use SixShop\MakerBundle\Generator\MigrationGenerator;

echo "🧪 SixShop Maker Bundle - Basic Functionality Test\n";
echo "=" . str_repeat("=", 50) . "\n\n";

$testDir = sys_get_temp_dir() . '/sixshop_basic_test_' . time();
$passed = 0;
$failed = 0;

function test(string $name, callable $test): void
{
    global $passed, $failed;
    echo "📋 Testing: {$name}... ";
    
    try {
        $result = $test();
        if ($result) {
            echo "✅ PASSED\n";
            $passed++;
        } else {
            echo "❌ FAILED\n";
            $failed++;
        }
    } catch (Exception $e) {
        echo "💥 ERROR: " . $e->getMessage() . "\n";
        $failed++;
    }
}

function setupTestDir(): string
{
    global $testDir;
    if (!is_dir($testDir)) {
        mkdir($testDir, 0755, true);
    }
    return $testDir;
}

function cleanupTestDir(): void
{
    global $testDir;
    if (is_dir($testDir)) {
        $iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($testDir, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );
        
        foreach ($iterator as $file) {
            if ($file->isDir()) {
                rmdir($file->getRealPath());
            } else {
                unlink($file->getRealPath());
            }
        }
        rmdir($testDir);
    }
}

// Test 1: Basic MigrationGenerator functionality
test("MigrationGenerator - Create Table", function() {
    $testDir = setupTestDir();
    $generator = new MigrationGenerator($testDir . '/migrations');
    
    $fields = [
        ['name' => 'id', 'type' => 'biginteger', 'null' => false],
        ['name' => 'name', 'type' => 'string', 'length' => 100, 'null' => false],
        ['name' => 'email', 'type' => 'string', 'length' => 255, 'null' => false, 'unique' => true]
    ];
    
    $result = $generator->generateMigration('users', $fields, 'create');
    
    if (!$result) {
        return false;
    }
    
    // Check if file was created
    $files = glob($testDir . '/migrations/*_create_users_table.php');
    return count($files) === 1;
});

test("MigrationGenerator - Supported Field Types", function() {
    $generator = new MigrationGenerator();
    $supportedTypes = $generator->getSupportedFieldTypes();
    
    $requiredTypes = ['string', 'integer', 'biginteger', 'text', 'boolean', 'decimal', 'json', 'timestamp'];
    
    foreach ($requiredTypes as $type) {
        if (!in_array($type, $supportedTypes)) {
            return false;
        }
    }
    
    return true;
});

test("MigrationGenerator - Complex Field Options", function() {
    $testDir = setupTestDir();
    $generator = new MigrationGenerator($testDir . '/migrations');
    
    $fields = [
        [
            'name' => 'price',
            'type' => 'decimal',
            'precision' => 10,
            'scale' => 2,
            'null' => false,
            'comment' => 'Product price'
        ],
        [
            'name' => 'config',
            'type' => 'json',
            'null' => true,
            'comment' => 'Configuration data'
        ]
    ];
    
    $result = $generator->generateMigration('products', $fields, 'create');
    
    if (!$result) {
        return false;
    }
    
    // Check if file was created and contains the expected content
    $files = glob($testDir . '/migrations/*_create_products_table.php');
    if (count($files) !== 1) {
        return false;
    }
    
    $content = file_get_contents($files[0]);
    return strpos($content, 'decimal') !== false && 
           strpos($content, 'json') !== false &&
           strpos($content, 'precision') !== false;
});

test("CLI Command Availability", function() {
    $binPath = __DIR__ . '/../bin/sixshop-maker';
    if (!file_exists($binPath)) {
        return false;
    }
    
    // Check if file is executable
    return is_executable($binPath);
});

test("Template Files Exist", function() {
    $requiredTemplates = [
        'composer.json.tpl.php',
        'config.php.tpl.php',
        'info.php.tpl.php',
        'src/Controller/Admin/Controller.php.tpl.php',
        'src/Controller/Api/Controller.php.tpl.php',
        'src/Entity/Entity.php.tpl.php',
        'src/Model/Model.php.tpl.php'
    ];
    
    $templateDir = __DIR__ . '/../templates/';
    
    foreach ($requiredTemplates as $template) {
        if (!file_exists($templateDir . $template)) {
            return false;
        }
    }
    
    return true;
});

test("Documentation Files", function() {
    $requiredFiles = [
        'README.md',
        'LICENSE',
        'composer.json'
    ];
    
    $rootDir = __DIR__ . '/../';
    
    foreach ($requiredFiles as $file) {
        if (!file_exists($rootDir . $file)) {
            return false;
        }
    }
    
    return true;
});

echo "\n" . str_repeat("=", 60) . "\n";
echo "📊 Test Results Summary\n";
echo str_repeat("=", 60) . "\n";
echo "✅ Passed: {$passed}\n";
echo "❌ Failed: {$failed}\n";

if ($failed === 0) {
    echo "📈 Success Rate: 100%\n";
    echo "\n🎉 All basic tests passed! The SixShop Maker Bundle is working correctly.\n";
} else {
    echo "📈 Success Rate: " . round(($passed / ($passed + $failed)) * 100, 1) . "%\n";
    echo "\n⚠️  Some tests failed. Please review the functionality.\n";
}

echo "\n💡 Manual Testing Commands:\n";
echo "- Extension generation: php bin/sixshop-maker\n";
echo "- Migration generation: php bin/sixshop-maker create_migration\n";
echo "- Help: php bin/sixshop-maker --help\n";
echo "- List commands: php bin/sixshop-maker list\n";

// Cleanup
cleanupTestDir();

echo "\n🧹 Test cleanup completed.\n";